﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ViewModel.User;
using EPIClientRssWP7.UserManagementService;

namespace ViewModel.User
{
    public class AuthentificationViewModel : UserViewModelBase
    {
        public AuthentificationViewModel()
        {
            Authenticate = new RelayCommand(ExecuteAuthentication, CanExecuteAuthentication);
        }

        private string messageAuth;
        public string MessageAuth
        {
            get {return messageAuth;}
            set
            {
                if (messageAuth != value)
                {
                    messageAuth = value;
                    OnPropertyChanged("MessageAuth", null);
                }
            }
        }

        private DataUser userBind;
        public DataUser UserBind
        { 
			get
			{
				return userBind;
			}
            set
            {
                if (userBind != value)
                {
                    userBind = value;
                    OnPropertyChanged("UserBind", null);
                }
            }
        }

        #region CommandAuthenticate
        public ICommand Authenticate
        { get; set; }


        private void ExecuteAuthentication(object param)
        {
            try
            { 
                UserService.authenticateUserCompleted += new EventHandler<EPIClientRssWP7.UserManagementService.authenticateUserCompletedEventArgs>(AuthenticateComplete);
                UserService.authenticateUserAsync(new authenticateUserRequest(userBind));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        private bool CanExecuteAuthentication(object sender)
        {
            return true;
        }

        public void AuthenticateComplete(object sender, authenticateUserCompletedEventArgs arg)
        {
            if (arg == null)
                throw new ArgumentNullException("Authenticate return null");
            DataUser user = arg.Result.authenticateUserResult;
            if (user != null)
            {
                ClientInformation userInfo = ClientInformation.Instance;
                userInfo.CurrentUser = user;
                userInfo.Authenticate = true;
                UserBind = user;
                MessageAuth = "Bonjour " + userBind.name;
            }
            else
                MessageAuth = "Invalid Email or Password";
        }
    }
        #endregion
}
;